package cn.sunxinao.pm.text;

import cn.sunxinao.pm.models.AbstractPet;
import cn.sunxinao.pm.models.AbstractUser;
import cn.sunxinao.pm.utils.IReadWriteTool;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class ReadWriteTool implements IReadWriteTool {
    @Override
    public List<AbstractPet> readAllPets(File file) {
        List<AbstractPet> pets = new ArrayList<>();
        try (Scanner userdata = new Scanner(new FileInputStream(file))) {
            while (userdata.hasNext()) {
                try {
                    Pet pet = Pet.ofString(userdata.nextLine());
                    pets.add(pet);
                } catch (NumberFormatException e) {
                    // do not add
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("提示: 无法访问文件，数据可能无法保存");
        }
        return pets;
    }

    @Override
    public boolean saveAllPets(List<AbstractPet> pets, File file) {
        try (FileWriter fileWriter = new FileWriter(file, false)) {
            for (AbstractPet pet : pets) {
                fileWriter.append(((Pet) pet).writeToString())
                    .append("\n");
            }
            fileWriter.flush();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("提示: 无法访问文件，数据可能无法保存");
            return false;
        }
    }

    @Override
    public List<AbstractUser> readAllUsers(File file) {
        List<AbstractUser> users = new ArrayList<>();
        try (Scanner userdata = new Scanner(new FileInputStream(file))) {
            while (userdata.hasNext()) {
                User user = User.ofString(userdata.nextLine());
                users.add(user);
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("提示: 无法访问文件，数据可能无法保存");
        }
        return users;
    }

    @Override
    public boolean saveAllUsers(List<AbstractUser> users, File file) {
        try (FileWriter fileWriter = new FileWriter(file, false)) {
            for (AbstractUser user : users) {
                fileWriter.append(((User) user).writeToString())
                    .append("\n");
            }
            fileWriter.flush();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("提示: 无法访问文件，数据可能无法保存");
            return false;
        }
    }
}
